package com.zhihaoliang.jobschedulertrain

import android.app.Service
import android.app.job.JobParameters
import android.app.job.JobService
import android.content.Intent
import android.nfc.Tag
import android.os.Handler
import android.os.Message
import android.os.Messenger
import android.os.RemoteException
import android.util.Log

/**
 * 创建日期：2020/3/21
 * 描述:
 * 作者:支豪亮
 */
private const val TAG = "MyJobService"

class MyJobService: JobService() {

    private var mActivityMessager:Messenger? =null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        mActivityMessager = intent?.getParcelableExtra(MESSENGER_INTENT_KEY)
        return Service.START_NOT_STICKY
    }

    override fun onStartJob(params: JobParameters?): Boolean {
        Log.e(TAG,"${Thread.currentThread()}:onStartJob")
        sendBroadcast(MSG_COLOR_START,params?.jobId?:1)

        //doSomeing

       /* val duration = params?.extras?.getLong(WORK_DURATION_KEY)?:return true
        Handler().postDelayed({
            sendBroadcast(MSG_COLOR_STOP, params?.jobId?:1)
            jobFinished(params, false)
        }, duration)
        Log.i(TAG, "on start job: ${params?.jobId}")*/

        //return true 表示有更多任务去做
        return true
    }

    override fun onStopJob(params: JobParameters?): Boolean {
        Log.e(TAG,"${Thread.currentThread()}:onStopJob")
        sendBroadcast(MSG_COLOR_STOP,params?.jobId?:1)
        //表示丢弃这个任务
        return false
    }

    private fun sendBroadcast(messageType:Int,params: Any?){

        if(mActivityMessager == null){
            Log.e(TAG,"${Thread.currentThread()}:服务没有启动。无法运行")
            return
        }
        val msg = Message.obtain().apply {
            what = messageType
            obj = params
        }
        try {
            mActivityMessager?.send(msg)
        }catch(e:RemoteException) {
            Log.e(TAG,"${e.toString()}")
        }

    }
}